const dbQuery = require('../model/db');
const joi = require('joi');
const {
	sendError,
	sendSuccess
} = require('../utils/sendFunction');

// 验证规则
// type keyword
const schemaSearch = joi.object({
	type: joi.number().valid(0, 1, 2).required().error(new Error('type不符合验证规则')),
})


// type keyword
const search = async function (req, res, next) {
	let info = req.query;

	if (!info.type || !info.keyword) {
		sendError(res, 200, 'type或keyword不能为空！');
		return;
	}

	try {
		await schemaSearch.validateAsync({
			type: info.type
		})
	} catch (error) {
		next(error);
		return;
	}

	// 歌曲
	if (info.type == 0) {
		let sqlStr = 'select music.*,singer.* from music inner join singer on music.singer_id = singer.singerid where singer.singer_name like ?'
		let result = await dbQuery(sqlStr, "%" + info.keyword + "%");
		if (result.length >= 0) {
			sendSuccess(res, '搜索成功！', {
				data: result
			})
		} else {
			sendError(res, 500, '搜索失败，请稍后再试！');
		}
		// 歌单
	} else if (info.type == 1) {
		let sqlStr = 'select * from gedan where gedan_title like ?'
		let result = await dbQuery(sqlStr, "%" + info.keyword + "%");
		if (result.length >= 0) {
			sendSuccess(res, '搜索成功！', {
				data: result
			})
		} else {
			sendError(res, 500, '搜索失败，请稍后再试！');
		}
		// mv
	} else {
		let sqlStr = 'select mv.*,singer.* from mv inner join singer on mv.singer_id = singer.singerid where mv.mv_name like ? or singer.singer_name like ?'
		let result = await dbQuery(sqlStr, ["%" + info.keyword + "%", "%" + info.keyword + "%"]);
		if (result.length >= 0) {
			sendSuccess(res, '搜索成功！', {
				data: result
			})
		} else {
			sendError(res, 500, '搜索失败，请稍后再试！');
		}
	}
}

module.exports = {
	search
}